package com.dronff.connection;

import com.dronff.BlockSend;
import com.dronff.functional.LockBefore;
import com.dronff.protocol.TangProtocol;
import com.dronff.stat.SocketChannelStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.socket.SocketChannel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class TangConnection implements BlockSend {

    private Channel channel;
    /**
     * 当前连接的状态
     */
    private SocketChannelStatus status;

    /**
     * 连接的ip
     */
    private String ip;
    /**
     * 连接的端口
     */
    private int port;

    @Override
    public void sendData(byte[] bytes, LockBefore lockBefore) throws InterruptedException {
        channel.writeAndFlush(
                Unpooled.wrappedBuffer(bytes)
        );
        Object lock = new Object();
        synchronized (lock){
            // 阻塞线程，等待返回数据
            lockBefore.doBefore(lock);
            lock.wait(1000);
        }
    }

    @Override
    public void sendTangProtocolData(TangProtocol tangProtocol, LockBefore lockBefore) throws InterruptedException {
        channel.writeAndFlush(
                tangProtocol
        );
        Object lock = new Object();
        synchronized (lock){
            // 阻塞线程，等待返回数据
            lockBefore.doBefore(lock);
            lock.wait();
        }
    }
}
